package com.hx.login.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hx.common.R;
import com.hx.common.api.MiaoshaGoodsService;
import com.hx.common.api.MiaoshaUserService;
import com.hx.common.common.enums.ResultStatus;
import com.hx.common.common.resultbean.ResultGeekQ;
import com.hx.common.domain.MiaoshaUser;
import com.hx.common.exception.GlobleException;

import com.hx.common.vo.LoginVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * @Author wonghiu
 * @Date 2021/6/4 15:28
 * @Version 1.0.1
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private MiaoshaUserService userService;

    @Reference(check = false)
    private MiaoshaGoodsService miaoshaGoodsService;

    @RequestMapping("/to_login")
    public String tologin(LoginVo loginVo, Model model) {
        return "login";
    }

    @RequestMapping("/do_login")
    @ResponseBody
    public R dologin(HttpSession session, @Valid LoginVo loginVo) {

        logger.info("do_login"+loginVo.toString());
        MiaoshaUser miaoshaUser = userService.login(loginVo);

        if (miaoshaUser!=null){
            // 如果认证通过，将用户信息存到session中
            session.setAttribute("loginUser",miaoshaUser);
        }else {
            return R.error("用户名或密码错误");
        }
        return R.ok();
    }
    @RequestMapping("/getuser")
    @ResponseBody
    public R getUserById(@RequestParam("userId") Long userId){
        return R.ok().setData(userService.getUserById(userId));
    }


    @RequestMapping("/checkException")
    @ResponseBody
    public R checkException(){
        throw new GlobleException(ResultStatus.ACCESS_LIMIT_REACHED);
    }
    @RequestMapping("/checkDubbo")
    @ResponseBody
    public R checkDubbo(){
        Integer res = miaoshaGoodsService.check();
        return R.ok().setData(res);
    }
//
//
//    @RequestMapping("/create_token")
//    @ResponseBody
//    public String createToken(HttpServletResponse response, @Valid LoginVo loginVo) {
//        logger.info(loginVo.toString());
//        String token = userService.createToken(response, loginVo);
//        return token;
//    }
}
